<template>
  <form-dialop
    :title="
      formType === 'edit' ? $t('user.RuleEditTitle') : $t('user.RuleViewTitle')
    "
    :visible="visible"
    width="30%"
    @handleClose="handleClose"
  >
    <template #content>
      <el-form
        ref="form"
        :model="formData"
        :rules="formRule"
        label-width="120px"
      >
        <el-form-item :label="$t('user.RoleName')" prop="roleName">
          <el-input
            v-if="formType === 'edit'"
            v-model="formData.roleName"
            :placeholder="$t('user.RuleNameRequired')"
            @keyup.enter.native="submit"
            clearable
            :disabled="true"
          />
          <span v-else>{{ formData.roleName }}</span>
        </el-form-item>
        <el-form-item :label="$t('user.RuleIsEnabled')" prop="isEnabled">
          <el-switch
            v-if="formType === 'edit'"
            :class="language === 'en' ? 'el-switch-en' : ''"
            v-model="formData.isEnabled"
            @keyup.enter.native="submit"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
          <span v-else>{{
            formData.isEnabled ? $t("common.Open") : $t("common.Close")
          }}</span>
        </el-form-item>
        <el-form-item :label="$t('user.RuleMenu')" prop="menus">
          <el-select
            v-if="formType === 'edit'"
            :placeholder="selectMenus.length?$t('user.RuleMenuRequired'):$t('user.PleasetickPermission')"
            v-model="formData.menus"
            multiple
            collapse-tags
          >
            <el-option
              v-for="menu in menusList"
              :label="menu.menuName"
              :value="menu.id"
              :key="menu.id"
              style="display: none"
            />
            <el-tree
              ref="RuleMenuTree"
              :disabled="true"
              :data="menusTree"
              @check-change="ruleMenuTreeCheckChange"
              :default-expand-all="true"
              :show-checkbox="true"
              :node-key="'id'"
              :props="ruleMenuTreeProps"
            ></el-tree>
          </el-select>
          <el-tree
            v-else
            ref="RuleMenuTree"
            :data="menusTree"
            @check-change="ruleMenuTreeCheckChange"
            :default-expand-all="true"
            :show-checkbox="true"
            :node-key="'id'"
            :props="ruleMenuTreeProps"
          ></el-tree>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="handleClose">{{ formType === 'edit' ? $t("common.cancel") : $t("common.confirm") }}</el-button>
      <el-button
        v-if="formType === 'edit'"
        type="primary"
        @click="submit"
        :disabled="loading"
        >{{ $t("common.confirm") }}</el-button
      >
    </template>
  </form-dialop>
</template>
<script lang="ts">
import Vue from "vue";
import FormDialop from "../../../components/Dialog/formDialog.vue";
import { AppModule } from "../../../store/modules/app";

export default Vue.extend({
  components: { FormDialop },
  computed: {
    language: () => AppModule.language,
  },
  data() {
    return {
      visible: false,
      loading: false,
      formId: null,
      formType: "view",
      formData: {
        roleName: "",
        isEnabled: 1,
        menus: [],
        menuCodes: []
      },
      formRule: {},
      selectMenus: [],
      menusList: [],
      ruleMenuTreeProps: {
        label: "menuName"
      },
      menusTree: [],
    };
  },
  methods: {
    async init(type: string, ruleData: any) {
      this.formId = ruleData.id;
      this.formType = type;


      await this.getRoleMenu();
      await this.getRoleDetail();
      this.visible = true;

      this.$nextTick(() => {
        (this.formData.menus as any).forEach((item:any) => {
          // 不能用setCheckedKeys这个内置方法，应该使用setChecked，目的防止父节点自动呗勾选
          (this as any).$refs["RuleMenuTree"].setChecked(item, true, false);
        })        
      });
      
    },
    submit() {
      (this as any).$refs.form.validate((valid: boolean) => {
        if (valid) {
          if (this.formType === "edit"&&this.selectMenus.length!==0) {
            this.loading = true;
            (this.formData as any).menuCodes = this.formData.menus.map((menuId: any) => (this as any).menusList.find((menu: any) => menu.id === menuId).menuCode);
            this.$systemTunnyApi
              .changeRuleById({ id: this.formId, ...this.formData })
              .then(() => {
                this.$emit("submit-success");
                this.handleClose();
                (this as any).$message.success(this.$t('markdowns.editSuccess'))
              })
              .finally(() => {
                this.loading = false;
              });
          }else{
            (this as any).$message.error(this.$t('user.PleasetickPermission'))
          }
        }
      });
    },
    handleClose() {
      this.formData.menus = [];
      this.visible = false;
    },
    ruleMenuTreeCheckChange() {
      this.selectMenus = (this as any).$refs["RuleMenuTree"].getCheckedNodes(false, true);
      (this as any).formData.menus = this.selectMenus.map(
        (menu: any) => menu.id
      );
    },
    getRoleMenu() {
      return this.$systemTunnyApi.getRuleMenuList(this.formId).then((result: any) => {
        this.menusList = result.data;
        this.menusList.map((menu: any) => {
          menu.disabled = this.formType != 'edit';
          return menu;
        });
        const menuTreeList = this.menusList.filter(
          (menu: any) => !menu.parentMenuId
        );
        this.menusList.forEach((menu: any) => {
          if (menu.parentMenuId) {
            const parentMenu: any =
              menuTreeList[
                menuTreeList.findIndex((m: any) => m.id == menu.parentMenuId)
              ];
            if (!parentMenu) return;
            if (!parentMenu.children) parentMenu.children = [];
            parentMenu.children.push(menu);
          }
        });
        this.menusTree = menuTreeList;
      });
    },
    async getRoleDetail() {
      try {
        const result = await this.$systemTunnyApi
          .getRuleById(this.formId);
  
        this.formData.roleName = result.data.roleName;
        this.formData.isEnabled = result.data.isEnabled;
        this.formData.menus = result.data.menus.map((menu: any) =>
          parseInt(menu.id)
        );
      } catch (error) {
        if (error.code == 600) {
          this.$message.warning(error.msg);
        }
      }
    },
  },
});
</script>